﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AnimationComp
{
    private Animation m_pAnimation;

    private bool m_bWork = false;
    private bool m_bIsLoop = false;
    private string m_sClipName = "";
    private float m_fPassTime = 0;
    private float m_fClipLength = 0;
    private int m_iCompCount = 0;
    private AnimationState m_pState;
    private AnimationClip m_pClip;

    private Action<string,int> m_pComp;
    public bool IsLoop
    {
        get { return m_bIsLoop; }
    }

    public AnimationComp(Animation animation,Action<string,int> compCB)
    {
        m_pAnimation =   animation;
        m_pComp = compCB;
    }

    public void Play(string clipName,bool isLoop)
    {
        if(m_pAnimation.GetClip(clipName) == null)
        {
            Debug.Log(clipName + "  is nil");
            return;
        }

        m_bWork = true;
        m_sClipName = clipName;
        m_bIsLoop = isLoop;
        m_fPassTime = 0;
        m_iCompCount = 0;
        m_pState = m_pAnimation[clipName];
        m_pClip = m_pAnimation.GetClip(clipName);
        m_fClipLength = m_pClip.length;
        m_pAnimation.wrapMode = isLoop ? WrapMode.Loop : WrapMode.Once;
        m_pAnimation.Play(clipName);
        m_pState.normalizedTime = m_fPassTime / m_fClipLength;
        m_pAnimation.Sample();
    }

    public void OnUpdate(float deltaTime)
    {
        if (m_bWork)
        {
            m_fPassTime += deltaTime;
            m_pState.normalizedTime = m_fPassTime / m_fClipLength;
            m_pAnimation.Sample();

            if(m_fPassTime >= m_fClipLength)
            {
                //过了一个周期
                if (m_bIsLoop)
                {
                    m_fPassTime = 0;
                }
                else
                {
                    m_fPassTime = 0;
                    m_bWork = false;
                }
                m_iCompCount++;
                if (m_pComp != null)
                    m_pComp(m_sClipName, m_iCompCount);
            }
        }
    }
}
